#!/usr/bin/perl -w

BEGIN {
	push @INC,"/usr/local/cluster/lib/perl";
}

use clutils;

# exit codes:
# 0 - nothing to do
# 1 - no such source archive or unable to open drbd
# 2 - drbd devices still in use
# 4 - unable to compile or install drbd
# 5 - unable to reload new drbd module

$code=$ARGV[0];
$::ARG_verbose=1;
if(!defined($code)) {
	exit 0;
}
if(! -f "/usr/src/cluster/$code") {
	exit 1;
}
logmsg("Attempting DRBD update from '$code'.");

# Check all drbd's are unconfigured and abort if not

if(-f "/proc/drbd") {
	open(FD,"/proc/drbd") or exit 1;
	$j=<FD>; $j=<FD>;
	while($j=<FD>) {
		chomp $j;
		@x=split(/\s+/,$j);
		if($x[$#x] ne "cs:Unconfigured") {
			logwarn("Unable to build update - DRBD still running.");
			exit 0;
		}
	}
	close(FD);
	system("/sbin/rmmod drbd 2>/dev/null");
}

# uncompress / compile new version

logmsg("Uncompressing DRBD sources...");
if(!chdir "/usr/src/cluster") {
	logwarn("Unable to change directory to '/usr/src/cluster'!");
	exit 0;
}
`tar xzf $code 2>/dev/null`;
if($?>>8) { exit 4; }
$s=$code;
$s =~ s/\.tar\.gz//;
chdir $s or exit 4;
chdir "drbd" or exit 4;
logmsg("Changed directory to /usr/src/cluster/$s/drbd - running make...");
`/usr/bin/make clean all 2>/dev/null`;
if($?>>8) { exit 4; }
chdir ".." or exit 4;
logmsg("Changed directory to /usr/src/cluster/$s - running make...");
`make tools 2>/dev/null`;
if($?>>8) { exit 4; }
logmsg("Running make install...");
`make install`;
if($?>>8) { exit 4; }
logmsg("DRBD '$s' built and installed successfully.");
# Copy to our drbd-bin directory.
if(-x "/sbin/cluster/useful/copy_drbd_bins") {
	system("/sbin/cluster/useful/copy_drbd_bins");
}
# For drbd 8.2.6 we must ensure drbdadm is not around
# since we don't use it, but kernel calls it!!
if(-f "/sbin/drbdadm") {
	rename("/sbin/drbdadm","/sbin/drbdadm.old");
	unlink("/sbin/drbdadm");
}
exit 0;

